// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/vector/vector_pool.h>

namespace kumo::pollux {
    namespace {
        /// Checks if specified type is supported and returns an index of the
        /// corresponding TypePool cache in VectorPool::vectors_ array. Return -1 if
        /// type is not supported, i.e. not a built-in singleton type.
        MELON_ALWAYS_INLINE int32_t toCacheIndex(const TypePtr &type) {
            static constexpr int32_t kNumCachedVectorTypes =
                    static_cast<int32_t>(TypeKind::HUGEINT) + 1;

            static std::array<const Type *, kNumCachedVectorTypes> kSupportedTypes = {
                BOOLEAN().get(),
                TINYINT().get(),
                SMALLINT().get(),
                INTEGER().get(),
                BIGINT().get(),
                REAL().get(),
                DOUBLE().get(),
                VARCHAR().get(),
                VARBINARY().get(),
                TIMESTAMP().get(),
                DATE().get(),
            };

            auto index = static_cast<int32_t>(type->kind());
            if (index < kNumCachedVectorTypes && kSupportedTypes[index] == type.get()) {
                return index;
            }

            return -1;
        }
    } // namespace

    VectorPtr VectorPool::get(const TypePtr &type, vector_size_t size) {
        auto cacheIndex = toCacheIndex(type);
        if (cacheIndex >= 0 && size <= kMaxRecycleSize) {
            return vectors_[cacheIndex].pop(type, size, *pool_);
        }
        return BaseVector::create(type, size, pool_);
    }

    bool VectorPool::release(VectorPtr &vector) {
        if (MELON_UNLIKELY(vector == nullptr)) {
            return false;
        }
        if (vector.use_count() != 1 || vector->size() > kMaxRecycleSize) {
            return false;
        }

        auto cacheIndex = toCacheIndex(vector->type());
        if (cacheIndex < 0) {
            return false;
        }
        return vectors_[cacheIndex].maybePushBack(vector);
    }

    size_t VectorPool::release(std::vector<VectorPtr> &vectors) {
        size_t numReleased = 0;
        for (auto &vector: vectors) {
            if (MELON_LIKELY(vector != nullptr)) {
                if (release(vector)) {
                    ++numReleased;
                }
            }
        }
        return numReleased;
    }

    void VectorPool::clear() {
        for (auto &vectorPool: vectors_) {
            vectorPool.clear();
        }
    }

    bool VectorPool::TypePool::maybePushBack(VectorPtr &vector) {
        // Check that this is a Flat Vector with an initialized, unique, and mutable
        // values Buffer and an uninitialized or unique and mutable nulls Buffer.
        if (!vector->is_writable() || !vector->is_flat_encoding() || !vector->values()) {
            return false;
        }
        if (size >= kNumPerType) {
            return false;
        }

        vector->prepare_for_reuse();
        vectors[size++] = std::move(vector);
        return true;
    }

    VectorPtr VectorPool::TypePool::pop(
        const TypePtr &type,
        vector_size_t vectorSize,
        memory::MemoryPool &pool) {
        if (size) {
            auto result = std::move(vectors[--size]);
            if (UNLIKELY(result->raw_nulls() != nullptr)) {
                // This is a recyclable vector, no need to check uniqueness.
                simd::memset(
                    const_cast<uint64_t *>(result->raw_nulls()),
                    bits::kNotNullByte,
                    bits::roundUp(std::min<int32_t>(vectorSize, result->size()), 64) / 8);
            }
            if (UNLIKELY(
                result->type_kind() == TypeKind::VARCHAR ||
                result->type_kind() == TypeKind::VARBINARY)) {
                simd::memset(
                    const_cast<void *>(result->values_as_void()),
                    0,
                    std::min<int32_t>(vectorSize, result->size()) * sizeof(StringView));
            }
            if (result->size() != vectorSize) {
                result->resize(vectorSize);
            }
            return result;
        }
        return BaseVector::create(type, vectorSize, &pool);
    }

    void VectorPool::TypePool::clear() {
        std::fill_n(vectors.begin(), kNumPerType, nullptr);
        size = 0;
    }
} // namespace kumo::pollux
